package org.example;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.thread.GlobalThreadPool;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * Hello world!
 */
public class App {

    private static final Log log = LogFactory.get();

    public static void main(String[] args) {

        // httpT();

        // enumT();

        threadT();
    }

    private static void httpT() {
        String result1 = HttpUtil.get("https://www.baidu.com");
        System.out.println(result1);
    }

    private static void enumT() {

        Map<String, Object> map = EnumUtil.getNameFieldMap(TestEnum.class, "type");

        for (String key : map.keySet()) {
            log.info("key= {} | value={}", key, map.get(key));
        }

    }

    private static void threadT() {
        int cnt = 5;
        CountDownLatch latch = ThreadUtil.newCountDownLatch(cnt);
        TimeInterval timer = DateUtil.timer();
        timer.start("main");
        for (int i = 0; i < cnt; i++) {
            ThreadUtil.execute(new TaskT(latch, timer));
        }

        log.info("submitTask times = {} ms ", timer.intervalRestart("main"));

        try {
            latch.await();
            log.info("--------------latch down = {} ms ", timer.intervalRestart("main"));
        } catch (InterruptedException e) {
            log.error(e, "ERROR {} ", e.getMessage());
        } finally {
            GlobalThreadPool.shutdown(false);
            log.info("--------------main end = {} ms ", timer.intervalRestart("main"));
        }

    }

    static class TaskT implements Runnable {

        private static final Log log = LogFactory.get();

        private CountDownLatch latch;
        private TimeInterval timer;

        public TaskT(CountDownLatch latch, TimeInterval timer) {
            this.latch = latch;
            this.timer = timer;
        }

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            timer.start(name);
            ThreadUtil.safeSleep(RandomUtil.randomInt(10) * 1000);

            log.info("threadName = {} | interval = {} s ", name, timer.intervalSecond(name));
            latch.countDown();
        }
    }

    // 定义枚举
    public enum TestEnum {
        TEST1("type1"), TEST2("type2"), TEST3("type3"), TEST4;

        private TestEnum(String type) {
            this.type = type;
        }

        private TestEnum() {}

        private String type;

        public String getType() {
            return this.type;
        }
    }

}
